﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;

namespace LINQPadLogParser
{
  internal sealed class MultipleLineManager : IEnumerable<W3CLogLine>
  {
    private readonly LineManager[] _managers;
    private readonly Uri _uri;

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public MultipleLineManager(string path, Uri uri, DateTime from, DateTime to)
    {
      _uri = uri;
      Path = path;
      _managers = Directory.GetFiles(path).Select(a => new LineManager(a, uri, from, to)).ToArray();
    }

    public string Path { [MethodImpl(MethodImplOptions.AggressiveInlining)] get; [MethodImpl(MethodImplOptions.AggressiveInlining)] private set; }

    public Uri Uri
    {
      [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return _uri; }
    }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public IEnumerator<W3CLogLine> GetEnumerator()
    {
      for (int i = 0; i < _managers.Length; i++)
      {
        foreach (W3CLogLine line in _managers[i])
        {
          yield return new W3CLogLine(line.Id*_managers.Length + i);
        }
      }
    }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    IEnumerator IEnumerable.GetEnumerator()
    {
      return GetEnumerator();
    }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public W3CLogLine? GetLine(int id)
    {
      int i = id%_managers.Length;
      W3CLogLine? line = _managers[i].GetLine(id/_managers.Length);
      if (line != null)
      {
        line = new W3CLogLine(line.Value.Id*_managers.Length + i);
      }
      return line;
    }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public string GetValue(int id, W3CColumn column)
    {
      return _managers[id%_managers.Length].GetValue(id/_managers.Length, column);
    }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public W3CColumn[] GetColumns(int id)
    {
      return _managers[id%_managers.Length].GetColumns(id/_managers.Length);
    }
  }
}